<template>
  <div>
    <MainContentSearchBarWrapper>
      <SearchBar inline>
        <template #normal>
          <el-form-item label="流程名称">
            <el-input v-model="tableForm.name" clearable placeholder="请输入流程名称"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="status" @change="setStatus(status)" placeholder="请选择流程状态">
              <el-option v-for="item in overviewList" :key="item.statusValue" :label="item.name"
                :value="item.statusValue" />
            </el-select>
          </el-form-item>
          <!--          <ins-cascader-filter @change="(value) => tableForm.queryInsIds = value"></ins-cascader-filter>-->
          <!-- <el-form-item label="创建人">
              <el-input
                v-model="tableForm.name"
                clearable
                placeholder="请输入创建人"
              ></el-input>
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="value" class="m-2" placeholder="Select" size="large">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item> -->
          <!-- <el-form-item class="">
            <el-button @click="resetForm">重置</el-button>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="$router.push('/flow/auto/marketingProcess/workTable')">
              新建流程
            </el-button>
          </el-form-item> -->
          <!-- wait(0,"等待发布"),
    publishing(1,"发布中"),
    published(2,"已发布"),
    pause(-1,"暂停中"),
    stop(-2,"已停止"); -->
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="primary" @click="$router.push(`/flow/auto/marketingProcess/workTable`)" v-has="['03020201']">
              新建流程
            </el-button>
          </el-form-item>
          <el-form-item>
            <!-- TODO 加权限 -->
            <el-button type="primary" @click="showExportData = true">导出</el-button>
          </el-form-item>
        </template>
        <!-- <template #toolbar>
          <el-form-item>
            <el-button type="primary" @click="$router.push('/flow/auto/marketingProcess/workTable')">
              新建流程
            </el-button>
          </el-form-item>
        </template> -->
      </SearchBar>
    </MainContentSearchBarWrapper>

    <div class="detail-data">
      <div class="data-content">
        <div v-for="(item, index) in overviewList" :key="index" class="detail-data-item">
          <div class="label">
            <div class="status-indicator" :class="[item.key]"></div>
            <span>{{ item.name }}</span>
          </div>
          <div class="value">
            {{ activityDetail[item.key] || 0 }}
          </div>
        </div>
      </div>
    </div>

    <LayoutTable ref="customerGroupRef" url="/flow/canvas/pageList" :param="tableForm">
      <el-table-column prop="name" label="流程名称" min-width="205" show-overflow-tooltip></el-table-column>
      <el-table-column prop="startType" label="类型" min-width="150">
        <template #default="scope">
          <div>
            <!-- {{ startTypeFilters(scope.row.startType) }} -->

            <span v-if="scope.row.startType == 1">单次执行</span>
            <span v-else>
              周期执行
              <br />
              {{ cycleTypeList[scope.row.cycleType] }}
              <span v-if="scope.row.cycleType == '7'">{{
                weekList[scope.row.cycleValue]
              }}</span>
              <span v-if="scope.row.cycleType == '2'">{{ scope.row.cycleValue }}号</span>
              {{ scope.row.cycleDayTime }} 执行
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="起止时间" min-width="165">
        <template #default="scope">
          <div>
            {{ $filters.dateFormat(scope.row.publishTime) }}-{{
              $filters.dateFormat(scope.row.invalidTime)
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="scope">
          <div>
            <span class="status-indicator" :class="[getStatusKey(scope.row.status)]"></span>
            {{ getStatus(scope.row.status) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="userGroupSymbol" label="客群" min-width="100"></el-table-column>
      <el-table-column prop="updateTime" label="累计进入/累计触达" min-width="100">
        <template #default="scope">
          <div>
            {{ `${scope.row.enterCount || 0}/${scope.row.reachCount || 0}` }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" v-has="[
        '03020202',
        '03020203',
        '03020204',
        '03020205',
        '03020206',
        '03020207',
        '03020208',
        '03020209',
        '03020210',
      ]">
        <template #default="scope">
          <div>
            <el-button v-show="showButton(scope.row.status, 'info')" link type="primary" @click="
              $router.push(
                `/flow/auto/marketingProcess/processDetail?id=${scope.row.id}`
              )
              " v-has="['03020202']">
              查看详情
            </el-button>
            <el-button link type="primary" @click="recoveryCanvas(scope.row)"
              v-show="showButton(scope.row.status, 'enable')" v-has="['03020209']">
              开启
            </el-button>
            <el-button link type="primary" @click="publishCanvas(scope.row)"
              v-show="showButton(scope.row.status, 'publish')" v-has="['03020203']">
              发布
            </el-button>
            <el-button link type="primary" @click="cancelPublish(scope.row)"
              v-show="showButton(scope.row.status, 'cancel-publish')" v-has="['03020204']">
              取消发布
            </el-button>
            <el-button link type="primary" @click="
              $router.push(
                `/flow/auto/marketingProcess/workTable?id=${scope.row.id}`
              )
              " v-show="showButton(scope.row.status, 'edit')" v-has="['03020205']">
              编辑
            </el-button>
            <el-button link type="primary" @click="copyCanvas(scope.row)" v-show="showButton(scope.row.status, 'copy')"
              v-has="['03020206']">
              复制
            </el-button>
            <el-button link type="primary" @click="pause(scope.row)" v-show="showButton(scope.row.status, 'pushed')"
              v-has="['03020208']">
              暂停
            </el-button>
            <el-button link type="primary" @click="del(scope.row)" v-show="showButton(scope.row.status, 'delete')"
              v-has="['03020207']">删除
            </el-button>
            <el-button link type="primary" @click="stop(scope.row)" v-show="showButton(scope.row.status, 'stop')"
              v-has="['03020210']">
              强制结束
            </el-button>
          </div>
        </template>
      </el-table-column>
    </LayoutTable>

    <exportData v-model:show-dialog="showExportData" :search-data="tableForm" title="营销流程" export-type="flowCanvasExport">
    </exportData>
  </div>
</template>
<script>
import CustomerApi from "@/api/customerApi.js";
import useFilter from "@/views/marketingProcess/composition/useFilter.ts";
import exportData from "@/components/exportData/exportData.vue";
export default {
  name: "processList",
  setup() {
    const { startTypeFilters, fetchTypeFilters, statusFilters } = useFilter();
    return {
      startTypeFilters,
      fetchTypeFilters,
      statusFilters,
    };
  },
  components: { exportData },
  data() {
    return {
      addGroup: false,
      showExportData: false,
      tabPosition: "list",
      status: -10,
      groupData: { id: null },
      formData: {},
      activityDetail: {},
      buttons: new Map(),
      cycleTypeList: {
        2: "每月",
        3: "每日",
        7: "每周",
      },
      weekList: {
        1: "一",
        2: "二",
        3: "三",
        4: "四",
        5: "五",
        6: "六",
        7: "七",
      },
      overviewList: [
        {
          name: "全部",
          key: "total",
          statusValue: -10,
        },
        {
          name: "运行中",
          key: "processing",
          statusValue: 2,
        },
        {
          name: "暂停中",
          key: "pause",
          statusValue: -1,
        },
        {
          name: "已结束",
          key: "stop",
          statusValue: -2,
        },
        {
          name: "草稿",
          key: "wait",
          statusValue: 0,
        },
      ],
      statusList: [
        {
          name: "全部",
          key: "total",
          statusValue: null,
        },
        {
          name: "运行中",
          key: "processing",
          statusValue: 1,
        },
        {
          name: "运行中",
          key: "processing",
          statusValue: 2,
        },
        {
          name: "暂停中",
          key: "pause",
          statusValue: -1,
        },
        {
          name: "已结束",
          key: "stop",
          statusValue: -2,
        },
        {
          name: "草稿",
          key: "wait",
          statusValue: 0,
        },
      ],
      tableForm: {
        name: "",
        status: [],
        queryInsIds: [],
      },
    };
  },
  created() {
    this.canvasCurrent();
    // buttonList: {
    //   draft: [], // 详情 复制 编辑 发布 删除
    //   pushing: "发布中", // 详情 复制 取消发布
    //   pushed: "运行中", // 详情 复制 暂停 强制结束
    //   pause: "暂停中", // 详情 复制 开启 强制结束
    //   end: "已结束", // 详情 复制 删除
    this.buttons.set(0, ["info", "copy", "edit", "publish", "delete"]);
    this.buttons.set(1, ["info", "copy", "cancel-publish"]);
    this.buttons.set(2, ["info", "copy", "pushed", "stop"]);
    this.buttons.set(-1, ["info", "copy", "enable", "stop"]);
    this.buttons.set(-2, ["info", "copy", "delete"]);
  },
  methods: {
    setStatus(status) {
      let All = null;
      let statusList = [];
      if (status == 1 || status == 2) {
        statusList = [1, 2];
      } else if (status == -10) {
        statusList = All; // -10查全部
      } else {
        statusList = [status];
      }
      this.tableForm.status = statusList;
    },

    showButton(status, type) {
      let btns = this.buttons.get(status);
      return btns.indexOf(type) !== -1;
    },

    getStatus(status) {
      return this.statusList.find((item) => item.statusValue === status)?.name;
    },

    getStatusKey(status) {
      return this.statusList.find((item) => item.statusValue === status)?.key;
    },

    // 暂停
    async pauseCanvas(row) {
      let rs = await CustomerApi.pauseCanvas({ id: row.id, name: row.name });
      if (rs.code == 200) {
        ElMessage.success("已暂停");
        this.onSearch();
      }
    },

    pause(row) {
      ElMessageBox.confirm("此操作将暂停该流程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.pauseCanvas(row);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消",
          });
        });
    },

    // 复制
    async copyCanvas(row) {
      let rs = await CustomerApi.copyCanvas({ id: row.id, name: row.name });
      if (rs.code == 200) {
        ElMessage.success("已复制");
        this.onSearch();
      }
    },

    // 强制结束
    async stopCanvas(row) {
      let rs = await CustomerApi.stopCanvas({ id: row.id, name: row.name });
      if (rs.code == 200) {
        ElMessage.success("已停止");
        this.onSearch();
      }
    },
    stop(row) {
      ElMessageBox.confirm("此操作将强制结束该流程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.stopCanvas(row);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 发布
    async publishCanvas(row) {
      let rs = await CustomerApi.publishCanvas({ id: row.id, name: row.name });
      if (rs.code == 200) {
        ElMessage.success("已发布");
        this.onSearch();
      }
    },
    // 取消发布
    async cancelPublishCanvas(row) {
      let rs = await CustomerApi.cancelPublishCanvas({
        id: row.id,
        name: row.name,
      });
      if (rs.code == 200) {
        ElMessage.success("已发布");
        this.onSearch();
      }
    },
    cancelPublish(row) {
      ElMessageBox.confirm("是否取消发布?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.cancelPublishCanvas(row);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 开启
    async recoveryCanvas(row) {
      let rs = await CustomerApi.recoveryCanvas({ id: row.id, name: row.name });
      if (rs.code == 200) {
        ElMessage.success("已恢复开启");
        this.onSearch();
      }
    },

    // 删除
    async delCanvas(row) {
      console.log("[ row ] >", row);
      let rs = await CustomerApi.delCanvas({ id: row.id, name: row.name });
      if (rs.code == 200) {
        ElMessage.success("已经删除");
        this.onSearch();
      }
    },

    del(row) {
      ElMessageBox.confirm("此操作将删除该流程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delCanvas(row);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消",
          });
        });
    },

    async canvasCurrent() {
      let rs = await CustomerApi.canvasCurrent();
      if (rs.code == 200) {
        this.activityDetail = rs.payload;
      }
    },

    toEditor(row) {
      this.addGroup = true;
      this.groupData = JSON.parse(JSON.stringify(row));
    },
    resetForm() {
      this.tableForm = {
        name: "",
        status: [null],
      };
      this.onSearch();
    },
    closeGroup(val, close) {
      this.addGroup = val;
      this.groupData = { id: null };
      if (!close) {
        this.onSearch();
      }
    },
    onSearch() {
      this.$nextTick(() => {
        this.$refs.customerGroupRef.search();
        this.canvasCurrent();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.detail {
  &-title {
    height: 56px;
    line-height: 56px;
    padding: 0 22px;
    font-size: 16px;
    font-weight: 700;
    color: rgba(0, 0, 0, 0.65);
    border-bottom: 1px solid rgba(0, 0, 0, 0.09);

    span {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
    }
  }

  &-data {
    display: flex;
    align-items: center;
    padding: 24px 0;
    border-top: 1px solid rgba(0, 0, 0, 0.09);

    &-item {
      width: 20%;
      height: 100%;
      font-size: 30px;
      font-weight: bold;
      line-height: 38px;
      padding: 0 0 0 40px;
      display: flex;
      justify-content: center;
      flex-direction: column;

      .label {
        font-size: 14px;
        font-weight: normal;
        line-height: 22px;
        margin-left: -14px;
        margin-bottom: 5px;
        display: flex;
        align-items: center;
      }
    }
  }
}

.data-content {
  //padding: 0 40px;
  //width: 100%;
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
  background: #f9faff;
}

.status-indicator {
  width: 6px;
  height: 6px;
  background: rgba(153, 153, 153, 0.68);
  border-radius: 50%;
  margin-right: 8px;
  display: inline-block;
}

.total {
  background: transparent;
}

.processing {
  background: rgba(50, 197, 255, 0.94);
}

.pause {
  background: rgba(255, 58, 48, 0.69);
}

.stop {
  background: rgba(97, 120, 255, 1);
}

.wait {
  background: rgba(153, 153, 153, 0.68);
}
</style>
